import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:岁亮亮
 * Date:2024-10-24
 * TIME:11:48
 */
public class TCPEchoClient {

    private Socket clientSocket = null;

    public  TCPEchoClient(String serverIP,int serverPort) throws IOException {
        clientSocket = new Socket(serverIP,serverPort);
    }
     public void start(){
         System.out.println("客户端启动");
         try(InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
             Scanner scannerConsole = new Scanner(System.in);
             Scanner scannerResponse = new Scanner(inputStream);
             PrintWriter printWriter = new PrintWriter(outputStream);
             while(true){
                 System.out.print("->");
                 if(!scannerConsole.hasNext()){
                     break;
                 }
                 //从控制台上读取 请求
                 //接收请求 并发送
                 //等待并接收响应
                 //打印响应

                 String request = scannerConsole.next();
                 //发送请求 这里发送的时候也用printwriter对象来发送 并以\n作为空白符结尾
                 // 这里是和服务器的scanner.next() 遥相呼应
                 printWriter.println(request);
                 //刷新缓冲区 I/O效率一般是很慢的  一般将网卡要发送的数据先放到内存缓冲区中 赞一波之后再一起发走 多个IO一起发送
                 printWriter.flush();
                 //读取服务器发回的响应 也和服务器相呼应
                 String response = scannerResponse.next();
                 System.out.println(response);

             }
         } catch (IOException e) {
             throw new RuntimeException(e);
         }

     }

    public static void main(String[] args) throws IOException {
        TCPEchoClient tcpEchoClient = new TCPEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }

}
